package cn.iocoder.yudao.module.pay.framework.impl.weixin;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.pay.order.dto.UnifiedOrderCreateDTO;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedPayChannelEnum;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedPayDisplayModeEnum;
import cn.iocoder.yudao.module.api.pay.order.vo.UnifiedOrderVO;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import lombok.extern.slf4j.Slf4j;

import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;

/**
 * 微信支付【App 支付】的 PayClient 实现类
 * 文档：<a href="https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_5_3.shtml">App 支付</a>
 *
 * @author 芋道源码
 */
@Slf4j
public class WxAppPayClient extends AbstractWxPayClient {

    public WxAppPayClient(WxPayClientConfig config) {
        super(UnifiedPayChannelEnum.WX_APP.getCode(), config);
    }

    @Override
    protected void doInit() {
        super.doInit(WxPayConstants.TradeType.APP);
    }

    @Override
    protected UnifiedOrderVO doUnifiedOrderV2(UnifiedOrderCreateDTO dto) throws WxPayException {
        WxPayUnifiedOrderRequest request = buildPayUnifiedOrderRequestV2(dto);
        WxPayAppOrderResult response = wxPayService.createOrder(request);
        UnifiedOrderVO.WxPayAppOrderResult result = BeanUtils.toBean(response, UnifiedOrderVO.WxPayAppOrderResult.class);
        return UnifiedOrderVO.waitingOf(UnifiedPayDisplayModeEnum.APP.getCode(), toJsonString(result),
                dto.getPayNo(), "", result);
    }

    @Override
    protected UnifiedOrderVO doUnifiedOrderV3(UnifiedOrderCreateDTO dto) throws WxPayException {
        WxPayUnifiedOrderV3Request request = buildPayUnifiedOrderRequestV3(dto);
        WxPayUnifiedOrderV3Result.AppResult response = wxPayService.createOrderV3(TradeTypeEnum.APP, request);
        UnifiedOrderVO.AppResult result = BeanUtils.toBean(response, UnifiedOrderVO.AppResult.class);
        return UnifiedOrderVO.waitingOf(UnifiedPayDisplayModeEnum.APP.getCode(), toJsonString(result),
                dto.getPayNo(), "", result);
    }

}
